package com.example.zbh.dsliao.utils.net;

/**
 * Created by yaolin on 15/11/19.
 */

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.zbh.dsliao.application.App;

import java.util.HashMap;
import java.util.Map;

//单例模式
public class VolleySingleton {

    //  private static VolleySingleton instance = new volleySingleTon();

    // 声明类本身的一个静态对象
    private static VolleySingleton instance;
    // 声明队列的对象
    private RequestQueue queue;
    private ImageLoader imageLoader;


    // 构造方法私有，防止外部类new此对象/被实例化
    private VolleySingleton() {
        // 初始化队列
        queue = getQueue();
        imageLoader = new ImageLoader(queue, new DoubleCache());
    }

    //public static VolleySingleton getInstance(){
    //return instance;
    //}
    // 公布一个静态方法，用于获取本类的实例
    public static VolleySingleton getInstance() {
        if (instance == null) {
            // 同步代码块，防止多线程同时执行
            synchronized (VolleySingleton.class) {
                if (instance == null) {
                    instance = new VolleySingleton();
                }
            }

        }
        return instance;
    }

    // 获取RequestQueue实例的方法
    private RequestQueue getQueue() {
        if (queue == null) {
            // 防止Activity的Context一直被占用
            queue = Volley.newRequestQueue(App.getContext());
        }
        return queue;
    }

    // 定义一个默认的Request的tag
    public static final String TAG = "VolleySingleton";

    public <T> void addRequest(Request<T> request) {
        request.setTag(TAG);
        queue.add(request);
    }

    // 重载一个方法，给Request添加自定义的tag
    public <T> void addRequest(Request<T> request, Object tag) {
        request.setTag(tag);
        queue.add(request);
    }

    public void addStringRequest(String url, Response.Listener<String> listener,
                                 Response.ErrorListener error) {
        StringRequest stringRequest = new StringRequest(url, listener, error) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        addRequest(stringRequest);

    }

//    public void PostRequest(String url,Response.Listener<String> listener,Response.ErrorListener error){
//        StringRequest stringRequest = new StringRequest(Request.Method.POST,url,listener,error);
//        addRequest(stringRequest);
//    }

    // 将Request从RequestQueue中移除，取消网络请求
    public void removeRequest(Object tag) {
        queue.cancelAll(tag);
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}

